﻿using System.Linq.Expressions;
using Lwllm.ArcengineProxy.Common;
using Lwllm.ArcengineProxy.Core.Annotations;
using Lwllm.ArcengineProxy.Core.Models;

namespace Lwllm.ArcengineProxy.Core.Implements
{
    public class BinaryResolve<T> : BaseResolve where T : BaseEntity
    {
        public BinaryResolve(Expression expression) : base(expression)
        {

        }
        public override string Build()
        {
            var whereClause = string.Empty;
            if (this.Expression is BinaryExpression binaryExpression)
            {
                string leftString = string.Empty;
                if (binaryExpression.Left is BinaryExpression)
                {
                    var binaryResolve = new BinaryResolve<T>(binaryExpression.Left);
                    leftString = binaryResolve.Build();
                }
                else
                {
                    if (binaryExpression.Left is MemberExpression memberExpression)
                    {
                        leftString = FieldNameAttribute.GetFieldName<T>(memberExpression.Member.Name);
                    }
                    else if (binaryExpression.Left is ConstantExpression constantExpression)
                    {
                        if (constantExpression.Type == typeof(string))
                        {
                            leftString = $"'{constantExpression.Value}'";
                        }
                        else
                        {
                            leftString = constantExpression.Value?.ToString();
                        }
                    }
                }

                var rightString = string.Empty;
                if (binaryExpression.Right is BinaryExpression)
                {
                    var binaryResolve = new BinaryResolve<T>(binaryExpression.Right);
                    rightString = binaryResolve.Build();
                }
                else
                {
                    if (binaryExpression.Right is MemberExpression memberExpression)
                    {
                        rightString = FieldNameAttribute.GetFieldName<T>(memberExpression.Member.Name);
                    }
                    else if (binaryExpression.Right is ConstantExpression constantExpression)
                    {
                        if (constantExpression.Type == typeof(string))
                        {
                            rightString = $"'{constantExpression.Value}'";
                        }
                        else
                        {
                            rightString = constantExpression.Value?.ToString();
                        }
                    }
                }

                var operatorString = GenericExtension.GetOperator(binaryExpression.NodeType);
                whereClause = $"({leftString} {operatorString} {rightString})";
            }

            return whereClause;
        }
    }
}
